把首頁做成PartialView,可以做到Ajax 不重整畫面的資料更新,這也是業界、面試常考技巧喔~ ,概念大家一定要知道,這一章跟之前的Ajax 不重整畫面讀出更多文章功能類似。沒看過的可以回去看看喔~
連結:.Net Core MVC Ajax 動態新增html - 載入更多文章功能
目標:
1.PartialView 的應用
步驟:
step1. 在_Layout.cshtml 加上新的一頁的連結
<li class="nav-item">
<a class="nav-link text-dark" href="~/TestPartialView">TestPartialView</a>
</li>
step2. ArtileController.cs 加上 Action 接收需求
[HttpGet("TestPartialView")]
public async Task<IActionResult> TestPartialView()
{
var model = await _article.GetArticle(null);
var result = new List<ArticleViewModel>();
if (model is not null && model.Count > 0)
{
result = model.Select(x => new ArticleViewModel
{
Id = x.Id,
ArticleContent = x.ArticleContent,
Title = x.Title
}).ToList();
TempData["ArticleLastId"] = result.Last().Id.ToString();
}
return View(result);
}
step3.新增TestPartialView.cshtml 在 View/Article 裡面
@model IEnumerable<ArticleViewModel>
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center mb-2">
<h1 class="display-4">TestPartial</h1>
</div>
<hr />
<div class="mb-3">
模糊查詢:
<input id="inputseatch" />
</div>
<div id="divPartial">
@await Html.PartialAsync("../PartialViews/_ArticlePartialView",Model)
</div>